<?php
declare (strict_types = 1);

namespace app\admin\controller\maichen;

use think\Request;
use think\facade\Config;
use think\facade\Request as Rq;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;

class Qifei
{
    protected $appid;
    protected $key;
    protected $baseUrl = 'http://qifei.yanqizhenxuan.cn/'; // 改用HTTP协议
    protected $client;

    public function __construct()
    {
        $this->appid = Config::get('qifei.appid');
        $this->key = Config::get('qifei.key');
        // 创建自定义的Client配置
        $this->client = new Client([
            'verify' => false,
            'curl' => [
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_MAXREDIRS => 5
            ],
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ],
            'timeout' => 30,
            'connect_timeout' => 10,
            'http_errors' => false,
            'allow_redirects' => true
        ]);
    }

    /**
     * 生成签名
     * @param array $params 请求参数
     * @return string
     */
    protected function generateSign(array $params): string
    {
        // 移除sign参数
        unset($params['sign']);
        
        // 按键名升序排序
        ksort($params);
        
        // 拼接参数
        $string = '';
        $i = 1;
        $times = count($params);
        foreach ($params as $key => $value) {
            if ($value !== '' && $value !== null) {
                $string .= $key . '=' . $value;
            }
            if ($i < $times ) {
                $string .= "&";
            }
            $i++;
        }   
        
        // 拼接密钥
        $string .= $this->key;
        // echo $string;exit;
        // echo $string;exit;
        // MD5加密
        return md5($string);
    }

    /**
     * 发送请求
     * @param string $url 接口地址
     * @param array $params 请求参数
     * @param string $method 请求方法
     * @return array
     */
    protected function sendRequest(string $url, array $params, string $method = 'GET'): array
    {
        try {
            // 添加appid
            $params['appid'] = $this->appid;
            
            // 生成签名
            $params['sign'] = $this->generateSign($params);
            
            // 发送请求
            $response = $this->client->request($method, $this->baseUrl . $url, [
                'query' => $params
            ]);
            
            $contents = $response->getBody()->getContents();
            \think\facade\Log::info('Qifei API Response: ' . $contents);
            
            return json_decode($contents, true) ?: [
                'status' => 0,
                'info' => '解析响应失败'
            ];
        } catch (\Exception $e) {
            // 记录错误日志
            \think\facade\Log::error('Qifei API Error: ' . $e->getMessage());
            return [
                'status' => 0,
                'info' => '请求失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 商品列表
     * @param Request $request
     * @return \think\Response
     */
    public function itemList(Request $request)
    {
        if (Rq::isPost()) {
            $params = $request->only([
                'shop',
                'keywords',
                'platform',
                'page',
                'page_size'
            ]);
            $result = $this->sendRequest('/api/Cid/itemList', $params);
            $data = [
                'code' => 0,
                'msg' => '成功',
                'data' => $result['data']['data'],
                'count' => $result['data']['total_count'],
            ];
            return $data;
        }
        
        //return $data;
        return view('item_list');
    }

    /**
     * 订单查询
     * @param Request $request
     * @return \think\Response
     */
    public function orderList(Request $request)
    {
        if (Rq::isPost()) {
        // 获取当前日期的时间戳
            
            
            $params = $request->only([
                'shop',
                'order_num',
                'goods_id',
                'item_name',
                'advertiser_id',
                'platform',
                'page',
                'page_size'
            ]);
            $start_time = Rq::post('start_time');
            if ($start_time) {
                $params['start_time'] = "{$start_time} 00:00:00";
                $params['end_time'] = "{$start_time} 23:59:59";
            } else {
                $start_time = strtotime("today");
                $end_time = $start_time + 86399;
                $start_date =  date('Y-m-d H:i:s', $start_time);
                $end_date =  date('Y-m-d H:i:s', $end_time);
                $params['start_time'] = $start_date;
                $params['end_time'] = $end_date;
            }
            $result = $this->sendRequest('/api/Cid/orderList', $params);
            $data = [
                'code' => 0,
                'msg' => '获取信息成功',
                'data' => $result['data']['data'],
                'count' => $result['data']['total_count'],
            ];
            return $data;
        }
        return view('order_list');
    }

    /**
     * 账户报表
     * @param Request $request
     * @return \think\Response
     */
    public function advertiserReportData(Request $request)
    {
        $params = $request->only([
            'start_time',
            'end_time',
            'advertiser_ids',
            'advertiser_name',
            'platform',
            'page',
            'page_size'
        ]);
        
        $result = $this->sendRequest('/api/Cid/advertserReportData', $params);
        return json($result);
    }

    /**
     * 计划报表
     * @param Request $request
     * @return \think\Response
     */
    public function planReportData(Request $request)
    {
        $params = $request->only([
            'start_time',
            'end_time',
            'advertiser_ids',
            'advertiser_name',
            'platform',
            'page',
            'page_size'
        ]);
        
        $result = $this->sendRequest('/api/Cid/planReportData', $params);
        return json($result);
    }

    public function index()
    {
        echo 32414;exit;
    }
} 